package com.lk.mall.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lk.mall.common.SystemConstant;
import com.lk.mall.mapper.AdminUserMapper;
import com.lk.mall.mapper.AdminUserTokenMapper;
import com.lk.mall.model.entity.AdminUser;
import com.lk.mall.model.entity.AdminUserToken;
import com.lk.mall.model.entity.User;
import com.lk.mall.model.entity.UserToken;
import com.lk.mall.service.IAdminUserService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * @author Lemonade
 * @description
 * @updateTime 2022/9/9 13:26
 */
@Service
public class AdminUserService extends ServiceImpl<AdminUserMapper, AdminUser> implements IAdminUserService {

    @Resource
    AdminUserMapper adminUserMapper;
    @Resource
    AdminUserTokenMapper adminUserTokenMapper;

    @Override
    public String login(String userName, String password) {

        // 1, 查询用户是否存在、是否锁定
        LambdaQueryWrapper<AdminUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AdminUser::getLoginUserName, userName).eq(AdminUser::getLoginPassword, password)
                .eq(AdminUser::getLocked, 0);
        AdminUser adminUser = adminUserMapper.selectOne(lambdaQueryWrapper);

        if (adminUser == null) {
            return SystemConstant.USER_NOT_FOUND;
        }

        if (adminUser.getLocked() == 1) {
            return SystemConstant.LOGIN_USER_LOCKED_ERROR;
        }

        // 2, 用户已存在且未锁定的情况下，根据 userId 查询 token
        AdminUserToken userToken = adminUserTokenMapper.selectById(adminUser.getAdminUserId());

        // 生成 token
        String token = System.currentTimeMillis() + "" + adminUser.getAdminUserId() + RandomUtil.randomNumbers(4);
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(token.getBytes());
            token = new BigInteger(1, md5.digest()).toString(16);

            token = token.length() == 31 ? token += "-" : token;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }

        Date now = new Date();
        Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000); // 48小时过期
        // 2.1, 如果 token 不存在，新增一条 token 数据
        if (userToken == null) {
            userToken = new AdminUserToken();
            userToken.setUserId(adminUser.getAdminUserId());
            userToken.setToken(token);
            userToken.setUpdateTime(now);
            userToken.setExpireTime(expireTime);

            // 新增一条 token 数据
            if (adminUserTokenMapper.insert(userToken) > 0) {
                return token;
            }
        } else {
            // 2.2, 如果 token 存在，更新 token 数据
            userToken.setToken(token);
            userToken.setUpdateTime(now);
            userToken.setExpireTime(expireTime);
            // 更新
            if (adminUserTokenMapper.updateById(userToken) > 0) {
                //修改成功后返回
                return token;
            }
        }

        return SystemConstant.USER_NOT_FOUND;
    }

    @Override
    public Boolean logout(Integer adminUserId) {
        return adminUserTokenMapper.deleteById(adminUserId) > 0;
    }
}
